import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.List;
import java.util.Optional;


public class ChatRoomUi extends Application {
    private static TextArea chatArea;
    private TextField messageField;
    private static ListView<String> memberListView;//成员列表视图
    private static ObservableList<String> members;//成员列表
    private String username;
    private Client client;
    private String taklTo ;//私聊目标

    public static void main(String[] args) {

        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        //聊天室启动需要先注册登录
        if (!showLoginDialog()) {

            System.exit(0);
        }


        primaryStage.setTitle("简单聊天室");

        //聊天记录框
        chatArea = new TextArea();
        chatArea.setWrapText(true);
        chatArea.setPrefSize(400, 300);
        chatArea.setEditable(false);

        //聊天输入框包括发送按钮
        messageField = new TextField();
        messageField.setPromptText("当前是群聊状态");
        messageField.setPrefWidth(300);
        Button sendButton = new Button("发送");
        sendButton.setOnAction(e -> sendMessage());

        VBox messageInputArea = new VBox(10);
        messageInputArea.setAlignment(Pos.CENTER);
        messageInputArea.setPadding(new Insets(10));
        messageInputArea.getChildren().addAll(messageField, sendButton);

        //首次注册时
        members = FXCollections.observableArrayList(client.getMember());

        memberListView = new ListView<>(members);



        Label memberLabel = new Label("聊天室成员");
        VBox memberBox = new VBox(memberLabel, memberListView);
        //增加监听方法 当选中成员时候进行私聊
        memberListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {

            taklTo = newValue;

            messageField.setPromptText("当前是私聊状态");
            System.out.println("Selected: " + taklTo);
        });

        memberBox.setPadding(new Insets(10));
        memberBox.setSpacing(10);
        memberBox.setAlignment(Pos.CENTER);

        ScrollPane chatScrollPane = new ScrollPane();
        chatScrollPane.setContent(chatArea);

        //构造主体窗口
        BorderPane root = new BorderPane();
        root.setPadding(new Insets(10));
        root.setCenter(chatScrollPane);
        root.setBottom(messageInputArea);
        root.setRight(memberBox);
        //点击窗口外边切换为群聊
        root.setOnMouseClicked(e->{
            memberListView.getSelectionModel().clearSelection();
            taklTo = "";
            messageField.setPromptText("当前是群聊状态");
            System.out.println("taklTo: " + taklTo);
        });
        primaryStage.setOnCloseRequest(event -> {
            //关闭窗体时 退出程序
            System.exit(0);
        });
        //窗体设置大小
        Scene scene = new Scene(root, 600, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    //消息发送
    private void sendMessage() {
        String message = messageField.getText();
        if (message == null || message.isEmpty()) {
            return;
        }
        if (taklTo == null || "".equals(taklTo)){ //群聊
            client.sendMessage("#@!"+message);//"#@!"群聊标识符
            chatArea.appendText("我对大家说:" + message + "\n");
        }else{
             //私聊
            client.sendMessage(taklTo+"@!#"+message);//@!#私聊标识符
            chatArea.appendText("我对"+taklTo+"说˵: " + message + "\n");

        }

        messageField.clear();
    }

    //弹窗注册昵称
    private boolean showLoginDialog() {
        //初始化弹窗
        Dialog<Boolean> dialog = new Dialog<>();
        dialog.setTitle("登录");
        dialog.setHeaderText("登录");

        TextField usernameField = new TextField();
        usernameField.setPromptText("请输入昵称");
        PasswordField passwordField = new PasswordField();
        passwordField.setPromptText("请输入密码");
        ButtonType loginButtonType  = new ButtonType("确认");
        ButtonType  cancelButtonType  = new ButtonType("取消");
        dialog.getDialogPane().setContent(new VBox(10, usernameField, passwordField));
        dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, cancelButtonType);
        dialog.setOnCloseRequest(event -> {
            dialog.close();
        });
        //点击事件
        dialog.setResultConverter(dialogButton -> {

            if (dialogButton == cancelButtonType) {
                //点击取消
                System.exit(0);
            }
            //点击确认
            if (dialogButton == loginButtonType) {
                String name = usernameField.getText();
                String password = passwordField.getText();
                if (isValidUsernameAndPassword(name, password)) {//登录校验
                    username = name;
                    //
                    client = new Client();
                    client.init(username);//登录成功 初始化客户端与服务端进行连接
                    client.sendMessage("1!@#"+username);//登录成功需要向服务端发送消息注册
                    return Boolean.TRUE;
                } else {
                    usernameField.clear();
                    passwordField.clear();
                    return null;
                }
            } else {
                return Boolean.FALSE;
            }
        });


        dialog.setResizable(false);
        Optional<Boolean> result = dialog.showAndWait();

        return result.orElse(Boolean.FALSE);
    }

    //判断用户名和密码是否正确
    private boolean isValidUsernameAndPassword(String username, String password) {
        if ("".equals(username) || username.contains("!") ||
        username.contains("@")  || username.contains("#")
                || username.contains("$")
                || username.contains("%")
                || username.contains("^")
                || username.contains("&")
                || username.contains("*")
                || username.contains("(")
                || username.contains(")")
        ){
            return false;
        }
        if (password.equals("123")){
            return true;
        }
        return  false;
    }

    public static void changeMerberUi(List<String> memberList){
        // 创建一个Runnable对象用于更新UI
        Runnable updateTask = new Runnable() {
            @Override
            public void run() {
                // 更新UI的代码
                if(members != null && memberListView!=null){
                    members.clear();
                    members.addAll(memberList);
                }
            }
        };
        Platform.runLater(updateTask);//FX更新UI需要把任务放入主线程中
    }

    public static void changeMessageUi(String message){
        // 创建一个Runnable对象用于更新UI
        Runnable updateTask = new Runnable() {
            @Override
            public void run() {
                // 更新UI的代码
                chatArea.appendText(message.substring(0,message.indexOf("#@!"))+"对大家说: "+
                        message.substring(message.indexOf("#@!")+3)+ "\n");
            }
        };
        Platform.runLater(updateTask);//FX更新UI需要把任务放入主线程中
    }

    public static void changeTaklToUi(String message){
        // 创建一个Runnable对象用于更新UI
        Runnable updateTask = new Runnable() {
            @Override
            public void run() {
                // 更新UI的代码
                chatArea.appendText(message.substring(0,message.indexOf("@!#"))+"对你说: "+
                        message.substring(message.indexOf("@!#")+3)+ "\n");
            }
        };
        Platform.runLater(updateTask);//FX更新UI需要把任务放入主线程中
    }
}
